﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;
using log4net;

namespace StockFinder.Services.PriceAnalysis
{
    /// <summary>
    /// Checks whether the last price bar is the largest volume up day the stock has had
    /// </summary>
    public class BiggestVolumeUpDayPriceAnalyser : IPriceAnalyser
    {
        private static readonly ILog _Log = LogManager.GetLogger(typeof(BiggestVolumeUpDayPriceAnalyser)); 

        public PriceAnalysisResult RunAnalysis(IOrderedEnumerable<DailyPrice> prices)
        {
            PriceAnalysisResult result = new PriceAnalysisResult();

            //1 check whether last action was an up day            
            DailyPrice lastPrice = prices.ElementAt(0);            
            DailyPrice penultimatePrice = prices.ElementAt(1);

            result.MostRecentPriceDate = lastPrice.PriceDate;

            try
            {
                if (lastPrice.AdjustedClose > penultimatePrice.AdjustedClose)
                {
                    //2. now check whether last volume was max volume
                    decimal maxVolume = prices.Max(p => p.Volume);

                    if (lastPrice.Volume == maxVolume)
                    {
                        result.Succeeded = true;

                        result.DaysOfPrices = PriceAnalyserHelper.DaysSince(prices.Min(p => p.PriceDate));

                        try
                        {
                            //3. compare to 3 month average volume
                            decimal averageVolume = prices.AverageVolume();

                            decimal volumeDifference = ((lastPrice.Volume - averageVolume) / averageVolume) * 100;

                            result.BaseDepth = volumeDifference;
                        }
                        catch (Exception exception)
                        {
                            _Log.ErrorFormat("An unexpected error occurred calculating average: {0}", exception);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _Log.Error(exception);                
            }            

            return result;
        }
    }
}
